<?php
/**
 * 订单模型
 *
 * Author:李强
 * Company:上海煦鸣网络科技有限公司
 * Date:2018-01-03
 */

namespace App\Models;


use App\Services\Service\Helper;

class Order extends CommonModel
{
    //
    protected $table = 'orders';

    public function param_options()
    {
        $params = [];
        $params['source'] = [
            "1" => '手工录入',
            "2" => '批量导入',
            "3" => '在线生成'
        ];
        $params['status'] = [
            "0" => "待接单",
            "1" => "接单中",
            "2" => "待审核",
            "3" => "待支付",
            "4" => "已完成",
            "-1" => "结束订单"
        ];
        return $params;
    }

    /**
     * 关联操作员信息
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    /**
     * 关联所属店铺
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function shop()
    {
        return $this->belongsTo(Shop::class, 'shop_id', 'id');
    }

    /**
     * 判断是否存在某个订单编号的信息
     *
     * @param $iid
     * @param int $id
     * @return bool
     */
    public static function isExist($order_no, $id = 0)
    {
        $data = self::where(['order_no' => $order_no])->when($id, function ($query) use ($id) {
            $query->where('id', '!=', $id);
        })->first();
        return is_null($data) ? false : true;
    }

    /**
     * 校验账号信息
     *
     * @param $account_no
     * @param int $shop_id
     * @return array
     */
    public static function check($account_no, $shop_id)
    {
         $interval = Config::getConfig('interval',0);
        $interval_diff = Config::getConfig('interval_diff',0);
        $result = [];
        $current = time();
        if ($interval > 0) {
            $start = date('Y-m-d', $current - 86400 * $interval);
            $count = self::where(['account_no' => $account_no, 'status' => 4, 'shop_id' => $shop_id])
                ->whereBetween('order_time', [$start . " 00:00:00", Helper::toDate()])
                ->count();
            if ($count) {
                $result['interval']['days'] = $interval;
                $result['interval']['count'] = $count;
            }
        }
        if ($interval_diff > 0) {
            $start = date('Y-m-d', $current - 86400 * $interval_diff);
            $count = self::where(['account_no' => $account_no, 'status' => 4])
                ->where('shop_id', '!=', $shop_id)
                ->whereBetween('order_time', [$start . " 00:00:00", Helper::toDate()])
                ->count();
            if ($count) {
                $result['interval_diff']['days'] = $interval;
                $result['interval_diff']['count'] = $count;
            }
        }
        return $result;
    }
}
